package system;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionFilter implements Filter {
    public SessionFilter() {
        super();
    }

    public void init(FilterConfig filterConfig) {
    }

    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException {
        String requestedSession =
            ((HttpServletRequest)servletRequest).getRequestedSessionId();
        String currentWebSession =
            ((HttpServletRequest)servletRequest).getSession().getId();
        boolean sessionOk =
            currentWebSession.equalsIgnoreCase(requestedSession);

        HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
        HttpServletResponse httpResponse =
            (HttpServletResponse)servletResponse;
        if (!sessionOk && requestedSession != null) {
            // the session has expired or renewed. Redirect request
            httpResponse.sendRedirect("/adfAuthentication?logout=true&amp;end_url=/faces/login.jspx");
        }
        SystemSecurity sercu = new SystemSecurity();
        if (!sercu.isAuthenticated()) {
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/faces/welcome");
        }
    }

    public void destroy() {
    }
}
